package com.front.managementfront.dictionary.service.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.front.managementfront.agreement.entity.HktsAgreement;
import com.front.managementfront.agreement.mapper.HktsAgreementMapper;
import com.front.managementfront.dictionary.entity.HktsDictionaryItem;
import com.front.managementfront.dictionary.entity.HktsDictionaryList;
import com.front.managementfront.dictionary.mapper.HktsDictionaryItemMapper;
import com.front.managementfront.dictionary.mapper.HktsDictionaryListMapper;
import com.front.managementfront.dictionary.service.IHktsDictionaryItemService;
import com.front.managementfront.fegin.IUserAppServiceClient;
import com.front.managementfront.utils.DictionaryConstant;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hkts.management.common.utils.CommonConstant;
import com.hkts.management.common.utils.Result;
import com.hkts.management.common.utils.ResultUtil;
import com.hkts.management.common.utils.SnowFlakeUtil;
import com.hkts.management.common.vo.UserBasicInfoVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yck
 * @since 2021-05-09
 */
@Service
@Transactional
public class HktsDictionaryItemServiceImpl extends ServiceImpl<HktsDictionaryItemMapper, HktsDictionaryItem> implements IHktsDictionaryItemService {


    @Autowired
    private HktsDictionaryItemMapper hktsDictionaryItemMapper;
    @Autowired
    private HktsDictionaryListMapper hktsDictionaryListMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IUserAppServiceClient iUserAppServiceClient;
    @Autowired
    private HktsAgreementMapper hktsAgreementMapper;


    @Override
    public PageInfo selectPage(Page<HktsDictionaryItem> page, HktsDictionaryItem hktsDictionaryItem) {
        PageHelper.startPage((int) page.getCurrent(), (int) page.getSize());
        QueryWrapper<HktsDictionaryItem> query = Wrappers.query();
        QueryWrapper<HktsDictionaryItem> entityWrapper = getEntityWrapper(query, hktsDictionaryItem);
        List<HktsDictionaryItem> hktsDictionaryItems = hktsDictionaryItemMapper.selectList(entityWrapper);
        PageInfo pageInfo = new PageInfo<>(hktsDictionaryItems);
        return pageInfo;
    }


    @Override
    public List<HktsDictionaryItem> selectList(HktsDictionaryItem hktsDictionaryItem) {
        QueryWrapper<HktsDictionaryItem> query = Wrappers.query();
        QueryWrapper<HktsDictionaryItem> entityWrapper = getEntityWrapper(query, hktsDictionaryItem);
        return hktsDictionaryItemMapper.selectList(entityWrapper);
    }
    /*
     *
     * 根据字典id查询
     * */

    @Override
    public List<HktsDictionaryItem> getByListId(String listId) {
        HktsDictionaryItem item = new HktsDictionaryItem();
        item.setIsDisable("0");
        item.setListId(listId);
        QueryWrapper<HktsDictionaryItem> query = Wrappers.query();
        QueryWrapper<HktsDictionaryItem> entityWrapper = getEntityWrapper(query, item);
        entityWrapper.orderByAsc(HktsDictionaryItem.ITEM_ORDER);
        List<HktsDictionaryItem> hktsDictionaryItems = hktsDictionaryItemMapper.selectList(entityWrapper);
        return hktsDictionaryItems;
    }

    /**
     * 公共查询条件
     *
     * @param entityWrapper
     * @return
     */
    public QueryWrapper<HktsDictionaryItem> getEntityWrapper(QueryWrapper<HktsDictionaryItem> entityWrapper, HktsDictionaryItem hktsDictionaryItem) {
        //条件拼接
        if (StringUtils.isNotBlank(hktsDictionaryItem.getCreateBy())) {
            entityWrapper.like(HktsDictionaryItem.CREATE_BY, hktsDictionaryItem.getCreateBy());
        }
            /*    if(StringUtils.isNotBlank(hktsDictionaryItem.getCreateTime())){
                entityWrapper.like(HktsDictionaryItem.CREATE_TIME,hktsDictionaryItem.getCreateTime());
                }
                if(StringUtils.isNotBlank(hktsDictionaryItem.getDelFlag())){
                entityWrapper.like(HktsDictionaryItem.DEL_FLAG,hktsDictionaryItem.getDelFlag());
                }*/
        if (StringUtils.isNotBlank(hktsDictionaryItem.getUpdateBy())) {
            entityWrapper.like(HktsDictionaryItem.UPDATE_BY, hktsDictionaryItem.getUpdateBy());
        }
             /*   if(StringUtils.isNotBlank(hktsDictionaryItem.getUpdateTime())){
                entityWrapper.like(HktsDictionaryItem.UPDATE_TIME,hktsDictionaryItem.getUpdateTime());
                }*/
        if (StringUtils.isNotBlank(hktsDictionaryItem.getIsDisable())) {
            entityWrapper.like(HktsDictionaryItem.IS_DISABLE, hktsDictionaryItem.getIsDisable());
        }
              /*  if(StringUtils.isNotBlank(hktsDictionaryItem.getItemOrder())){
                entityWrapper.like(HktsDictionaryItem.ITEM_ORDER,hktsDictionaryItem.getItemOrder());
                }*/
        if (StringUtils.isNotBlank(hktsDictionaryItem.getItemValue())) {
            entityWrapper.like(HktsDictionaryItem.ITEM_VALUE, hktsDictionaryItem.getItemValue());
        }
        if (StringUtils.isNotBlank(hktsDictionaryItem.getIsHotCategories())) {
            entityWrapper.eq(HktsDictionaryItem.IS_HOT_CATEGORIES, hktsDictionaryItem.getIsHotCategories());
        }
        if (StringUtils.isNotBlank(hktsDictionaryItem.getListId())) {
            entityWrapper.eq(HktsDictionaryItem.LIST_ID, hktsDictionaryItem.getListId());
        }
        if (StringUtils.isNotBlank(hktsDictionaryItem.getUnit())) {
            entityWrapper.like(HktsDictionaryItem.UNIT, hktsDictionaryItem.getUnit());
        }
        return entityWrapper;
    }

    /*
     * 模糊查询字典项数据 将搜索记录缓存到redis
     * */
    @Override
    public List<HktsDictionaryItem> hktsDictionaryItemsGetByKeyAndItemName(String key, String itemName) {
        HktsDictionaryList list = new HktsDictionaryList();
        list.setDictionaryKey(key);
        list.setIsDisable(CommonConstant.IS_NOT_DISABLE);
        QueryWrapper<HktsDictionaryList> queryWrapper = Wrappers.query();
        queryWrapper.eq(HktsDictionaryList.DICTIONARY_KEY, key);
        HktsDictionaryList hktsDictionaryList = hktsDictionaryListMapper.selectOne(queryWrapper);
        if (hktsDictionaryList == null) {
            return null;
        }
        HktsDictionaryItem item = new HktsDictionaryItem();
        item.setListId(hktsDictionaryList.getId());
        item.setItemValue(itemName);
        item.setIsDisable(CommonConstant.IS_NOT_DISABLE);
        QueryWrapper<HktsDictionaryItem> queryWrapperItem = Wrappers.query();
        getEntityWrapper(queryWrapperItem, item);
        queryWrapperItem.orderByAsc(HktsDictionaryItem.ITEM_ORDER);
        List<HktsDictionaryItem> hktsDictionaryItems1 = hktsDictionaryItemMapper.selectList(queryWrapperItem);
        /*
         * 缓存部分逻辑
         * redisTemplate.opsForList().range(ErpProperties.ASPHALT_STOCK,0,-1)
         * DictionaryConstant
         * */
        Result<UserBasicInfoVo> userBasicInfoVoResult = iUserAppServiceClient.remoteUserBasicInfo();
        List<String> range = redisTemplate.opsForList().range(DictionaryConstant.DICTIONARY + userBasicInfoVoResult.getResult().getId() + ":" + key, 0, -1);
        List<String> itemList = new ArrayList<String>();
        if (range.isEmpty()) {

            itemList.add(itemName);
            redisTemplate.opsForList().leftPushAll(DictionaryConstant.DICTIONARY + userBasicInfoVoResult.getResult().getId() + ":" + key, itemList);
        } else {
            redisTemplate.delete(DictionaryConstant.DICTIONARY + userBasicInfoVoResult.getResult().getId() + ":" + key);

            if (range.contains(itemName)) {
                Iterator<String> iterator = range.iterator();
                while (iterator.hasNext()) {
                    iterator.remove();
                    break;
                }
            }
            itemList.add(itemName);
            itemList.addAll(range);
            redisTemplate.opsForList().rightPushAll(DictionaryConstant.DICTIONARY + userBasicInfoVoResult.getResult().getId() + ":" + key, itemList);
        }
        return hktsDictionaryItems1;
    }

    @Override
    public List<HktsDictionaryItem> getHotCategories(String key) {
        HktsDictionaryList list = new HktsDictionaryList();
        list.setDictionaryKey(key);
        list.setIsDisable(CommonConstant.IS_NOT_DISABLE);
        QueryWrapper<HktsDictionaryList> queryWrapper = Wrappers.query();
        queryWrapper.eq(HktsDictionaryList.DICTIONARY_KEY, key);
        HktsDictionaryList hktsDictionaryList = hktsDictionaryListMapper.selectOne(queryWrapper);
        if (hktsDictionaryList == null) {
            return null;
        }
        HktsDictionaryItem item = new HktsDictionaryItem();
        item.setListId(hktsDictionaryList.getId());
        item.setIsDisable(CommonConstant.IS_NOT_DISABLE);
        item.setIsHotCategories(DictionaryConstant.IS_HOT_CATEGORIES);
        QueryWrapper<HktsDictionaryItem> queryWrapperItem = Wrappers.query();
        getEntityWrapper(queryWrapperItem, item);
        queryWrapperItem.orderByAsc(HktsDictionaryItem.ITEM_ORDER);
        List<HktsDictionaryItem> hktsDictionaryItems1 = hktsDictionaryItemMapper.selectList(getEntityWrapper(queryWrapperItem, item));
        return hktsDictionaryItems1;
    }

    @Override
    public void hktsDictionaryItemSave(HktsDictionaryItem hktsDictionaryItem) {
        /*
         *排序字段是否为空如果不为空查找最大排序号
         * */
        hktsDictionaryItem.setDelFlag(CommonConstant.IS_NOT_DELETE);
        Result<UserBasicInfoVo> userBasicInfoVoResult = iUserAppServiceClient.remoteUserBasicInfo();
        if (hktsDictionaryItem.getItemOrder() == null) {
            Integer max = hktsDictionaryItemMapper.selectMaxOrderByListId(hktsDictionaryItem.getListId());
            if (max == null) {
                hktsDictionaryItem.setItemOrder(1);
            } else {
                hktsDictionaryItem.setItemOrder(max + 1);
            }
        }
        /*
         * 校验是否有重名
         *
         * */
        QueryWrapper<HktsDictionaryItem> queryWrapper = Wrappers.query();
        queryWrapper.ne(StringUtils.isNotBlank(hktsDictionaryItem.getId()), HktsDictionaryItem.ID, hktsDictionaryItem.getId());
        queryWrapper.eq(HktsDictionaryItem.LIST_ID, hktsDictionaryItem.getListId());
        queryWrapper.eq(HktsDictionaryItem.ITEM_VALUE, hktsDictionaryItem.getItemValue());
        List<HktsDictionaryItem> hktsDictionaryItems = hktsDictionaryItemMapper.selectList(queryWrapper);
        if (hktsDictionaryItems.size() > 0) {
            throw new RuntimeException("字典项值重复！");
        }
        if (StringUtils.isNotBlank(hktsDictionaryItem.getId())) {
            hktsDictionaryItem.setUpdateTime(LocalDateTime.now());
            hktsDictionaryItem.setUpdateBy(userBasicInfoVoResult.getResult().getNickName());
        } else {
            hktsDictionaryItem.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
            hktsDictionaryItem.setCreateTime(LocalDateTime.now());
            hktsDictionaryItem.setCreateBy(userBasicInfoVoResult.getResult().getNickName());
            hktsDictionaryItem.setIsDisable(CommonConstant.IS_NOT_DISABLE);
        }
        this.saveOrUpdate(hktsDictionaryItem);
    }

    @Override
    public List<HktsDictionaryItem> getHktsDictionaryItemList(String listId) {
        HktsDictionaryItem item = new HktsDictionaryItem();
        item.setListId(listId);
        item.setIsDisable("0");
        QueryWrapper<HktsDictionaryItem> query = Wrappers.query();
        QueryWrapper<HktsDictionaryItem> entityWrapper = getEntityWrapper(query, item);
        List<HktsDictionaryItem> hktsDictionaryItems = hktsDictionaryItemMapper.selectList(entityWrapper);
        return hktsDictionaryItems;
    }

    @Override
    public List<HktsDictionaryItem> getHktsDictionaryByAgreementId(String agreementId) {
        QueryWrapper<HktsDictionaryItem> queryWrapper = Wrappers.query();
        queryWrapper.lambda().eq(HktsDictionaryItem::getAgreementId, agreementId);
        List<HktsDictionaryItem> hktsDictionaryItems = hktsDictionaryItemMapper.selectList(queryWrapper);
        return hktsDictionaryItems;
    }

    @Override
    public Result<HktsAgreement> getAgreementContent(String cargoTypeId, String contractId) {
        HktsDictionaryItem hktsDictionaryItem = hktsDictionaryItemMapper.selectById(cargoTypeId);
        if(StringUtils.isBlank(hktsDictionaryItem.getAgreementId())){
            QueryWrapper<HktsAgreement> queryWrapper = Wrappers.query();
            queryWrapper.lambda().eq(HktsAgreement::getId,"434163643593003008");
            HktsAgreement hktsAgreement = hktsAgreementMapper.selectOne(queryWrapper);
            hktsAgreement.setAgreementContent(null);
            return ResultUtil.data(hktsAgreement);
        }
        QueryWrapper<HktsAgreement> queryWrapper = Wrappers.query();
        queryWrapper.lambda().eq(HktsAgreement::getId,hktsDictionaryItem.getAgreementId());
        HktsAgreement hktsAgreement = hktsAgreementMapper.selectOne(queryWrapper);
        hktsAgreement.setAgreementContent(null);
   /*     if(StringUtils.isBlank(contractId)){
            //测试永
            String conent = hktsAgreement.getAgreementContent().replace("${carcode}", "冀A1234");
            conent=  conent.replace("${price}","3000");
            hktsAgreement.setAgreementContent(conent);
            return ResultUtil.data(hktsAgreement);
        }*/

        //Todo 将协议价格车牌等内容写进合同内

        return ResultUtil.data(hktsAgreement);
    }

    @Override
    public Map<String, Object> getDictItemByItemId(String itemId) {
        Map<String,Object> map=new HashMap<String,Object>();
        HktsDictionaryItem hktsDictionaryItem = hktsDictionaryItemMapper.selectById(itemId);
        map.put("cargoTypeName",hktsDictionaryItem.getItemValue());
        if(StringUtils.isNotBlank(hktsDictionaryItem.getAgreementId())){
            HktsAgreement one = hktsAgreementMapper.selectById(hktsDictionaryItem.getAgreementId());
            map.put("id",one.getId());
            map.put("agreementName",one.getAgreementName());
        }else{
            HktsAgreement one1 = hktsAgreementMapper.selectById("434163643593003008");
            map.put("id",one1.getId());
            map.put("agreementName",one1.getAgreementName());
        }
        return map;
    }
}
